package com.shouhuobao.take.home;

import android.app.Activity;
import android.content.Intent;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.app.AppCaptureActivity;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.dialog.DialogMgr;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.AppLogic;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.model.UserBean;
import com.shouhuobao.station.R;
import com.shouhuobao.take.active.ActiveMainActivity;
import com.shouhuobao.take.input.ParcelInputActivity;
import com.shouhuobao.take.model.ActiveConfigBean;
import com.shouhuobao.take.model.BannerBean;
import com.shouhuobao.take.model.IndexBean;
import com.shouhuobao.take.model.ParcelBean;
import com.shouhuobao.take.parcel.ParcelActivity;
import com.shouhuobao.take.parcel.ParcelSearchActivity;
import com.shouhuobao.take.utils.StringUtils;
import com.shouhuobao.take.weight.banner.Banner;
import com.shouhuobao.take.weight.banner.BannerConfig;
import com.shouhuobao.take.weight.banner.Transformer;
import com.shouhuobao.take.weight.banner.listener.OnBannerListener;
import com.shouhuobao.take.weight.banner.loader.GlideImageLoader;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import droid.frame.activity.title.TitleRes;
import droid.frame.app.Callback;
import droid.frame.utils.android.SharedPref;

/**
 * 代收首页
 *
 * @author coffee<br>
 *         2017年6月2日下午6:29:38
 */
public class HomeFragment extends BaseHomeFragment implements OnClickListener, OnBannerListener {

    private EditText mSearchInput;
    private Button mSearchButton;
    private TextView mParcelCount1, mParcelCount2;
    //    private ConvenientBanner mBanner;
    private Banner mBanner;


    /**
     * 标记#onResume的时候是否需要刷新首页接口
     */
    private boolean request2refresh = false;


    @Override
    protected void findViewById() {
        setContentView(R.layout.take_home);
        super.findViewById();
        getAppTitle().setTitle(null, new TitleRes("火箭驿站"), null);
        mSearchInput = (EditText) findViewById(R.id.take_search_input);
        mSearchButton = (Button) findViewById(R.id.take_search_button);
        mParcelCount1 = (TextView) findViewById(R.id.take_count1);
        mParcelCount2 = (TextView) findViewById(R.id.take_count2);
        //        mBanner = (ConvenientBanner) findViewById(R.id.convenientBanner);
        mBanner = (Banner) findViewById(R.id.banner);
        mSearchInput.setOnClickListener(this);
        mSearchButton.setOnClickListener(this);
        findViewById(R.id.take_item1_layout).setOnClickListener(this);
        findViewById(R.id.take_item2_layout).setOnClickListener(this);
        findViewById(R.id.take_item3_layout).setOnClickListener(this);
        findViewById(R.id.take_item4_layout).setOnClickListener(this);

        findViewById(R.id.home_scan).setOnClickListener(this);
        super.type = 0;
        //
        setBannerData(null);
        AppHttp.getInstance().takeIndex();
        UserBean userBean = AppCache.getUser();
        if (null == userBean.getStationId()) {
            AppHttp.getInstance().getUserInfo();
        } else {
            AppHttp.getInstance().queryActiveConfig();
        }
    }

    /**
     * 设置banner数据
     */
    public void setBannerData(ArrayList<BannerBean> items) {
        //衡水
        //                if (!StringUtils.isEmpty(userBean.getCode()) && userBean.getCode().startsWith("318")) {
        //                    items.add(new BannerBean(R.drawable.home_banner_1));
        //                    items.add(new BannerBean(R.drawable.home_banner_2));
        //                } else {
        //                    items.add(new BannerBean(R.drawable.home_banner_2));
        //                }
        if (mBanner == null) {
            return;
        }
        //设置banner样式
        mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置banner加载器
        mBanner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        mBanner.setBannerList(items);
        //设置banner动画效果
        mBanner.setBannerAnimation(Transformer.Default);
        //设置自动轮播，默认为true
        mBanner.isAutoPlay(true);
        //设置轮播时间
        mBanner.setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        mBanner.setIndicatorGravity(BannerConfig.CENTER);
        mBanner.setOnBannerListener(this);
        //banner设置方法全部调用完毕时最后调用
        mBanner.start();

    }

    @Override
    public void onClick(View v) {
        if (AppCache.getUser().getStationId() == null) {
            return;
        }
        Intent intent = null;
        switch (v.getId()) {
            // 扫码
            case R.id.home_scan:
                intent = new Intent();
                intent.setClass(getActivityContext(), AppCaptureActivity.class);
                startActivityForResult(intent, 100);
                break;
            case R.id.take_search_input:
                mSearchInput.setFocusable(true);
                mSearchInput.setFocusableInTouchMode(true);
                mSearchInput.requestFocus();
                setSoftInput(mSearchInput, true);
                break;
            // 搜索按钮
            case R.id.take_search_button:
                if (TextUtils.isEmpty(mSearchInput.getText()) == false) {
                    mSearchInput.setFocusable(false);
                    mSearchInput.setFocusableInTouchMode(false);
                    mSearchInput.clearFocus();
                    showLoadingDialog(null);
                    AppHttp.getInstance().takeParcelSearch(1, mSearchInput.getText().toString());
                }
                break;
            // 在店包裹
            case R.id.take_item1_layout:
                intent = new Intent();
                intent.setClass(getActivityContext(), ParcelActivity.class);
                intent.putExtra("item", 0);
                startActivityForResult(intent, 1002);
                break;
            // 已取走包裹
            case R.id.take_item2_layout:
                intent = new Intent();
                intent.setClass(getActivityContext(), ParcelActivity.class);
                intent.putExtra("item", 1);
                startActivityForResult(intent, 1002);
                break;
            // 包裹签收
            case R.id.take_item3_layout:
                intent = new Intent();
                intent.setClass(getActivityContext(), ParcelInputActivity.class);
                startActivityForResult(intent, 101);
                break;
            // 取货验证
            case R.id.take_item4_layout:
                intent = new Intent();
                intent.setClass(getActivityContext(), com.shouhuobao.take.parcel.ParcelCheckActivity.class);
                startActivityForResult(intent, 1002);
                break;
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MsgID.take_index:
                final ReqResult<IndexBean> result1 = JSON.parser(msg.obj, IndexBean.class);
                if (checkLoginStatus(result1)) {
                    getActivityContext().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            IndexBean index = result1.getResult();
                            mParcelCount1.setText(index.getParcelCount1());
                            mParcelCount2.setText(index.getParcelCount2());
                        }
                    });
                }
                return true;
            //录入、取走
            case MsgID.take_parcel_input:
            case MsgID.take_parcel_away:
                ReqResult<?> result2 = JSON.parser(msg.obj);
                if (checkLoginStatus(result2)) {
                    getActivityContext().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            request2refresh = true;
                        }
                    });
                } else {
                    showToast(result2.getMessage());
                }
                return false;
            // 检索包裹--搜索结果
            case MsgID.take_parcel_search:
                cancelLoadingDialog();
                ReqResult<ParcelBean> result = JSON.parseList(msg.obj, ParcelBean.class);
                if (checkLoginStatus(result)) {
                    String str = mSearchInput.getText().toString();
                    Intent intent = new Intent();
                    intent.setClass(getActivityContext(), ParcelSearchActivity.class);
                    intent.putExtra("keywords", str);
                    startActivity(intent);
                } else {
                    showToast(result.getMessage());
                }
                return false;
            //请求活动数据
            case MsgID.query_active_config_data:
                final ReqResult<ActiveConfigBean> result3 = JSON.parser(msg.obj, ActiveConfigBean.class);
                getActivityContext().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (checkLoginStatus(result3)) {
                            ActiveConfigBean configBean = result3.getResult();
                            if (configBean == null) {
                                return;
                            }
                            updateActiveView(configBean);
                        } else {
                            showToast(result3.getMessage());
                        }
                    }
                });
                return false;
            default:
                return super.handleMessage(msg);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        mBanner.startAutoPlay();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (request2refresh) {
            UserBean userBean = AppCache.getUser();
            if (null == userBean.getStationId()) {
                AppHttp.getInstance().getUserInfo();
            }
        }
        request2refresh = false;
    }

    @Override
    public void onStop() {
        super.onStop();
        request2refresh = true;
        //结束轮播
        mBanner.stopAutoPlay();
    }

    /**
     * 更新活动标题提示
     */
    private void updateActiveView(final ActiveConfigBean configBean) {
        String takeStr = "";
        String sendStr = "";
        //代收活动
        if (configBean.getRanking1() != null) {
            takeStr = "代收排名第" + configBean.getRanking1().getMyrank() + "名";
        } else {
            takeStr = "";
        }
        //寄件活动
        if (configBean.getRanking2() != null) {
            sendStr = "寄件排名第" + configBean.getRanking2().getMyrank() + "名";
        } else {
            sendStr = "";
        }
        findViewById(R.id.tipsLL).setVisibility(View.VISIBLE);
        ((TextView) findViewById(R.id.tip_right_tv)).setText("点击进入");
        LinearLayout takeTipsLL = (LinearLayout) findViewById(R.id.take_tips_LL);
        if (isEmpty(takeStr) && isEmpty(sendStr)) {
            updateTitleView(1, "");
        } else if (!isEmpty(takeStr) && isEmpty(sendStr)) {
            ((TextView) findViewById(R.id.tipsTV)).setText("冲榜单活动火热进行中，您当前" + takeStr);
        } else if (isEmpty(takeStr) && !isEmpty(sendStr)) {
            ((TextView) findViewById(R.id.tipsTV)).setText("冲榜单活动火热进行中，您当前" + sendStr);
        } else {
            ((TextView) findViewById(R.id.tipsTV)).setText("冲榜单活动火热进行中，您当前" + takeStr + "," + sendStr);
        }
        if (!isEmpty(takeStr) || !isEmpty(sendStr)) {
            if ("周一".equals(getWeekOfDate(new Date())) && SharedPref.isFirstOpen("active")) {
                SharedPref.setFirstOpen("active", false);
                DialogMgr.showActiveTips(getActivityContext(), new Callback() {
                    @Override
                    public void onDialogDismiss() {
                        startActivity(ActiveMainActivity.class);
                    }
                });
            } else {
                if (!"周一".equals(getWeekOfDate(new Date()))) {
                    SharedPref.setFirstOpen("active", true);
                }
            }
        }
        takeTipsLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppHttp.getInstance().queryActiveConfig();
                AppLogic.contextToActive(getActivityContext(), "com.shouhuobao.take.active.ActiveMainActivity");
            }
        });
    }

    /**
     * 根据日期获得星期
     *
     * @param date
     * @return
     */
    private String getWeekOfDate(Date date) {
        String[] weekDaysName = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int intWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        return weekDaysName[intWeek];
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK && requestCode == 100) {
            String result = data.getStringExtra("result");
            if (isEmpty(result)) {
                return;
            }
            mSearchInput.setText(result);
            showLoadingDialog(null);
            AppHttp.getInstance().takeParcelSearch(1, result);
        } else if (resultCode == Activity.RESULT_OK && requestCode == 101) {
            request2refresh = true;
            AppHttp.getInstance().takeIndex();
        } else if (resultCode == Activity.RESULT_OK && requestCode == 1002) {
            request2refresh = true;
            AppHttp.getInstance().takeIndex();
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * banner的点击事件
     *
     * @param position
     */
    @Override
    public void OnBannerClick(int position) {
        if (null == AppCache.getUser().getStationId() || mBanner.getBannerBeanList() == null
                || mBanner.getBannerBeanList().size() == 0 || null == mBanner.getBannerBeanList().get(position).getOpenType()) {
            return;
        }
        if (StringUtils.isEmpty(mBanner.getBannerBeanList().get(position).getImgUrl())) {
            if (0 != mBanner.getBannerBeanList().get(position).getImgRes()) {
                AppLogic.disposeBannerData(getActivityContext(), mBanner.getBannerBeanList().get(position));
            } else {
                return;
            }
        }
        AppLogic.disposeBannerData(getActivityContext(), mBanner.getBannerBeanList().get(position));
    }
}

